package com.attendance.chdingtask.controller;

import com.attendance.chdingtask.model.CorpUserDetail;
import com.attendance.chdingtask.utils.dingApi.JwtUtils;
import com.attendance.chdingtask.utils.exception.BizException;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;
import java.util.UUID;

public class BaseController {
    protected void checkNull(Object obj, String msg) {
        if (obj == null||obj.equals("")) {
            throw new BizException(msg);
        }
        if (obj instanceof List){
            if (checkList((List)obj)){
                throw new BizException(msg);
            }
        }
        if (obj instanceof Map){
            if (checkMap((Map)obj)){
                throw new BizException(msg);
            }
        }
    }
    protected Boolean checkList(List list) {
        if (list==null||list.size()<=0) {
            return  true;
        }
        return  false;
    }
    protected Boolean checkMap(Map map) {
        if (map==null||map.size()<=0) {
            return  true;
        }
        return  false;
    }


    /**
     * 鉴权 获取用户信息
     *
     * @param request
     * @return
     */
    public CorpUserDetail getUserInfo(HttpServletRequest request) {
        String authorization = request.getHeader("Authorization");
        CorpUserDetail user = JwtUtils.unsign(authorization, CorpUserDetail.class);
        return user;
    }

    protected String createUUIDString() {

        return UUID.randomUUID().toString().replace("-", "");
    }

    /**
     * 获取调用地址真实ip
     * @param request
     * @return
     */
    protected String getRequestIp(HttpServletRequest request) {
        String ip =null;
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("X-Forwarded-For");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
//            if(ip.equals("127.0.0.1") || ip.equals("0:0:0:0:0:0:0:1")){
//                //根据网卡取本机配置的IP
//                InetAddress inet=null;
//                try {
//                    inet = InetAddress.getLocalHost();
//                } catch (UnknownHostException e) {
//                    e.printStackTrace();
//                }
//                ip= inet.getHostAddress();
//            }
        }
        if (ip != null) {
            //对于通过多个代理的情况，最后IP为客户端真实IP,多个IP按照','分割
            int position = ip.indexOf(",");
            if (position > 0) {
                ip = ip.substring(0, position);
            }
        }
        return ip;
    }



}
